<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Validate;
use think\model\concern\SoftDelete;
use think\Facade\Log;

class WxDailyRetain extends Common
{
    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if (isset($post['limit'])) {
            $limit = $post['limit'];
        } else {
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    /**
     *  添加品牌
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => [],
            'token'  => \think\facade\Request::token('__ZlServer_Token__', 'sha1')
        ];

        if (!$this->allowField(true)->save($data)) {
            $result['status'] = false;
            $result['msg'] = '保存失败';
        }

        return $result;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if (isset($post['time']) && $post['time'] != "") {
            $date_array = explode('到', $post['time']);
            $sutime = trim($date_array[0]);
            $eutime = trim($date_array[1]);
            $where[] = ['refDate', ['EGT', $sutime], ['ELT', $eutime], 'and'];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['refDate DESC'];
 
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        return $list;
    }

    /**
     * @param $date
     * @param $retainInfo
     *
     * @return mixed
     */
    public function updateBillInfo($date, $retainInfo)
    {
        // 数据格式化
        $retainList = $this->deal_WeChat_response($retainInfo);

        if(count($retainList['uv']) > 0) {
            // 格式化日期
            $vals = explode("-", $date);
            if(count($vals) != 3) { 
                return error_code(10051);
            } 
            
            $date = $vals[0].$vals[1].$vals[2];
            // 清理数据
            $this->where(['refDate'=>$date])->delete();
            
            // 插入数据
            $this->startTrans(); 
            $this->insertAll($retainList['uv']);               
            $this->commit(); 
        }
    }

    public function doDailyRetain($date) 
    {
        $payment_code = 'wechatpay';
        
        ///判断支付方式是否开启
        $paymentsModel = new Payments();
        $paymentInfo = $paymentsModel->getPayment($payment_code, $paymentsModel::PAYMENT_STATUS_YES);
        if(!$paymentInfo){
            return error_code(10050);
        }
        $conf = json_decode($paymentInfo['params'],true);
        // 开始微信对账
        $payment = \org\Payment::create($payment_code, $conf);
        $daiyRetain = $payment->getDailyRetain($date);

        if($daiyRetain['status']) {
            $this->updateBillInfo($date, $daiyRetain['data']);
        }
    }
 
    /**
     * 微信对账单数据处理
     * @param $response 对账单数据
     * @return array 返回结果
     */
    private function deal_WeChat_response($retainInfo)
    {
        $result  = array();
        $result['uv'][] = array(
            'refDate'               => $retainInfo['ref_date'],                 // 日期
            'visitUvNew'            => $retainInfo['visit_uv_new'][0]['value'], // 新增
            'visitUv'               => $retainInfo['visit_uv'][0]['value'],     // 日活
        );
       
        return $result;
    }

    /**
     * 按天统计商户下面的数据
     */
    public function statistics($day)
    { 
        $resUvNew = $this->field('refDate as day, visitUvNew as nums')->where("TIMESTAMPDIFF(DAY,refDate,now()) < 7 and TIMESTAMPDIFF(DAY,refDate,now()) > 0")->select();
        $resUv = $this->field('refDate as day, visitUv as nums')->where("TIMESTAMPDIFF(DAY,refDate,now()) < 7 and TIMESTAMPDIFF(DAY,refDate,now()) > 0")->select();
       
        $day  = $day - 1;
        $daysUvNew = [];
        $daysUv = [];
        $d    = [];
        for ($i = $day + 1; $i >= 1; $i--) {
            $d[] = date('d', strtotime('-' . $i . ' day')) . '日';
            $daysUvNew[date('Ymd', strtotime('-' . $i . ' day'))] = 0;
            $daysUv[date('Ymd', strtotime('-' . $i . ' day'))] = 0;
        }

        foreach ($resUvNew as $v) {
            $daysUvNew[$v['day']] = $v['nums'];
        }
        
        $uvNew = [];
        foreach ($daysUvNew as $v) {
            $uvNew[] = $v;
        }
        
        foreach ($resUv as $v) {
            $daysUv[$v['day']] = $v['nums'];
        }
        
        $uv = [];
        foreach ($daysUv as $v) {
            $uv[] = $v;
        }
       
        return ['day' => $d, 'uvNew' => $uvNew, 'uv' => $uv];
    }
}
